import React, { Component } from "react";
import { Button, Popconfirm, Radio, Row, Tabs, Table, Modal, Icon } from "antd";
import { connect } from "dva";
import { typeOptions } from "components/flowdetailpannel/FlowParameters";
import TransactorSelect from "./TransactorSelect";
import FlowParamsSelector from "./FlowParamsSelector";
// import FlowRelationSelector from "./FlowRelationSelector";
import styles from "./UserTaskSelector.less";

const { TabPane } = Tabs;
const RadioGroup = Radio.Group;

const typeLabelMap = { STA: "人员", ORG: "组织", ROL: "角色" };
const tabKeyValueMap = { 1: "STA", 2: "VAR", 3: "INIT" };

const RelationStandardMap = {
  NONE: "无",
  ASSIGNEE: "办理人",
  INITIATOR: "流动启动人",
};
const RelationNodeMap = {
  NONE: "无",
  PREVIOUS: "上一节点",
  SPECIFY: "指定节点",
};
const RelationRelationMap = {
  NONE: "无",
  DEPARTMENT_STAFF: "同部门人员",
  DEPARTMENT_LEADER: "同部门领导",
  SUPERIOR_DEPARTMENT_STAFF: "上级部门人员",
  SUPERIOR_DEPARTMENT_LEADER: "上级部门领导",
};

//  Deprecated. Previously referenced by:
//    src/components/flowdetailpannel/UserSelectorModal.jsx(Deprecated also)
//    src/components/flowdetailpannel/UserTaskDetail.jsx

@connect(({ FlowChart }) => ({
  // 在src/components/flowdetailpannel/NodeSelected.jsx加载数据
  noticeTypeData: FlowChart.noticeTypeData,
}))
class UserTaskSelector extends Component {
  relationColumns = [
    {
      title: "节点",
      dataIndex: "node",
      render: (text, record) =>
        record.node === "SPECIFY"
          ? record.selectNodeName
          : RelationNodeMap[text],
    },
    {
      title: "基准",
      dataIndex: "benchmark",
      render: (text) => RelationStandardMap[text],
    },
    {
      title: "关系",
      dataIndex: "relation",
      render: (text) => RelationRelationMap[text],
    },
  ];

  constructor(props) {
    super(props);
    const { noticeTypeData } = props;
    this.setupNoticeTypeMap(noticeTypeData || []);
    this.state = {
      activeKey: "1",
      candidateUsersVisible: false,
      selectedSTAKeys: [],
      selectedVARKeys: [],
      visible: false,
      // relationPopVisible: false,
    };
  }

  componentDidMount() {
    const { selectedModel = {} } = this.props;
    this.initActiveKey(selectedModel);
  }

  setupNoticeTypeMap = (datas) => {
    if (!this.noticeMap && datas.length > 0) {
      this.noticeMap = datas.reduce((map, data) => {
        map[data.code] = data;
        return map;
      }, {});
    }
  };

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { selectedModel } = this.props;
    const { noticeTypeData = [] } = nextProps;
    this.setupNoticeTypeMap(noticeTypeData);

    if ((nextProps.selectedModel || {}).id !== selectedModel.id) {
      this.initActiveKey(nextProps.selectedModel);
      this.setState({
        // eslint-disable-line
        selectedSTAKeys: [],
        selectedVARKeys: [],
      });
    }
  }

  initActiveKey = (selectedModel) => {
    const { properties = {} } = (selectedModel || {}).model || {};
    const { candidateUsers = [] } = properties;
    const userSelectValue = this.getUserSelectValue(candidateUsers);
    let activeKey = "1";
    if (userSelectValue === "VAR") {
      activeKey = "2";
    }
    if (userSelectValue === "INIT") {
      activeKey = "3";
    }
    this.setState({ activeKey });
  };

  getUserSelectValue = (candidateUsers) => {
    if (candidateUsers.length === 0) {
      if (this.userSelectValue === "STA" || this.userSelectValue === "VAR") {
        return this.userSelectValue;
      }
      this.userSelectValue = "None";
      return "None";
    } else if (candidateUsers.some((ele) => ele.type === "INIT")) {
      // this.hqdisable = true;
      this.userSelectValue = "INIT";
      return "INIT";
    } else if (candidateUsers.some((ele) => ele.type === "VAR")) {
      // this.hqdisable = true;
      this.userSelectValue = "VAR";
      return "VAR";
    } else {
      this.userSelectValue = "STA";
      return "STA";
    }
  };

  onTab = (key) => {
    const { selectedModel = {} } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const { candidateUsers = [], relativeRelations = [] } = properties;
    const variableDataSource = candidateUsers.map(
      ({ name, code, varType: type }) => ({
        name,
        code,
        type,
      }),
    );
    if (
      (candidateUsers.length > 0 && candidateUsers[0].name !== "") ||
      (variableDataSource.length > 0 && variableDataSource[0].name !== "") ||
      (relativeRelations.length > 0 && relativeRelations[0].name !== "")
    ) {
      Modal.warning({
        title: "切换办理人设置方式提醒",
        content: (
          <div>
            <p>删除当前办理人记录后，才能切换到</p>
            <p>其他办理人设置方式</p>
          </div>
        ),
        onOk: () => {},
        okText: "知道了",
      });
    } else {
      this.onTabChange(key);
    }
  };

  onTabChange = (key) => {
    const { disable } = this.props;
    if (disable) {
      return;
    }

    this.setState({ activeKey: key });

    const value = tabKeyValueMap[key];
    const {
      changeModelVariableRef,
      handleChangeProperties,
      handleUsersSelect,
      noticeTypeData,
      selectedModel = {},
    } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const { candidateUsers = [] } = properties;
    let changeValue = [];
    this.userSelectValue = value;
    if (value === "INIT") {
      changeValue = [{ name: "", type: "INIT", code: "" }];
      if (properties.multiinstance_type !== "None") {
        handleChangeProperties(
          "multiinstance_type",
          "None",
          selectedModel.model,
          selectedModel.shape,
          false,
        );
      }
    } else if (value === "None") {
      // 以前还有'请选择'选项，value为'None'
      if (properties.multiinstance_type !== "None") {
        handleChangeProperties(
          "multiinstance_type",
          "None",
          selectedModel.model,
          selectedModel.shape,
          false,
        );
      }
    } else if (value === "STA") {
      this.setState({ selectedSTAKeys: [] });
    } else if (value === "VAR") {
      this.setState({ selectedVARKeys: [] });
    }
    handleUsersSelect(changeValue, noticeTypeData[0]);
    const codes = candidateUsers
      .filter((v) => v.type === "VAR")
      .map((v) => v.code);
    changeModelVariableRef(codes, selectedModel, false);
  };

  handleVarVisible = (visible) => {
    this.setState({ visible });
  };

  handleUserVisible = (v) => {
    this.setState({ candidateUsersVisible: v });
  };

  /*
  handleRelationVisible = (visible) => {
    this.setState({
      relationPopVisible: visible,
    });
  };
  */

  renderButtons = (type, candidateUsers) => {
    const {
      selectedSTAKeys = [],
      selectedVARKeys = [],
      selectedRELKeys = [],
    } = this.state;
    const {
      changeModelVariableRef,
      disable,
      handleDeleteUsers,
      handleDeleteRelation,
      selectedModel = {},
    } = this.props;
    let onAdd = this.handleVarVisible;
    let suffix = "变量";
    let keys = selectedVARKeys;
    if (type === "STA") {
      onAdd = this.handleUserVisible;
      suffix = "人员";
      keys = selectedSTAKeys;
    }
    if (type === "REL") {
      onAdd = this.handleRelationVisible;
      suffix = "关系";
      keys = selectedRELKeys;
    }
    return (
      <Row
        className={styles.buttons}
        justify="space-between"
        style={{ marginTop: 16 }}
        type="flex"
      >
        <Button disabled={disable} onClick={() => onAdd(true)}>
          添加
        </Button>
        {!disable && keys.length > 0 ? (
          <Popconfirm
            placement="top"
            title={`请确认是否删除当前选中${suffix}`}
            onConfirm={() => {
              this.setState(
                {
                  selectedSTAKeys: [],
                  selectedVARKeys: [],
                  selectedRELKeys: [],
                },
                () => {
                  if (type === "VAR") {
                    changeModelVariableRef(keys, selectedModel, false);
                  }
                  if (type === "REL") {
                    handleDeleteRelation(candidateUsers, false, keys);
                  }
                  handleDeleteUsers(candidateUsers, false, keys);
                  this.forceUpdate();
                },
              );
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>删除</Button>
          </Popconfirm>
        ) : (
          <Button disabled>删除</Button>
        )}
        {!disable && candidateUsers.length > 0 ? (
          <Popconfirm
            placement="top"
            title={`请确认是否删除所有${suffix}`}
            onConfirm={() => {
              this.setState(
                {
                  selectedSTAKeys: [],
                  selectedVARKeys: [],
                  selectedRELKeys: [],
                },
                () => {
                  const codes = candidateUsers.map(({ code }) => code);
                  if (type === "VAR") {
                    changeModelVariableRef(codes, selectedModel, false);
                  }
                  if (type === "REL") {
                    handleDeleteRelation(candidateUsers, true);
                  }
                  handleDeleteUsers(candidateUsers, true);
                  this.forceUpdate();
                },
              );
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>全删</Button>
          </Popconfirm>
        ) : (
          <Button disabled>全删</Button>
        )}
      </Row>
    );
  };

  onAddVariables = (addedRows, rows, selectedModel) => {
    const {
      changeModelVariableRef,
      handleUsersSelect,
      noticeTypeData,
    } = this.props;
    const codes = addedRows.map(({ code }) => code);
    changeModelVariableRef(codes, selectedModel, true);
    const selectedRows = addedRows.concat(rows);
    const selectData = selectedRows.map(({ name, code, type }) => ({
      name,
      code,
      type: "VAR",
      varType: type,
    }));
    handleUsersSelect(selectData, noticeTypeData[0]);
    this.setState({ visible: false });
  };

  // 添加相对关系
  onAddRelation = (param, rows) => {
    const { handleRelationSelect } = this.props;
    const selectedRows = [param].concat(rows);
    handleRelationSelect(selectedRows);
    this.handleRelationVisible(false);
  };

  getSelectIndexes = (candidateUsers, variableDataSource) => {
    const { activeKey, selectedSTAKeys, selectedVARKeys } = this.state;
    let selectedKeys;
    let dataSource;
    const indexes = [];
    switch (activeKey) {
      case "1":
        selectedKeys = selectedSTAKeys;
        dataSource = candidateUsers;
        break;
      case "2":
        selectedKeys = selectedVARKeys;
        dataSource = variableDataSource;
        break;
      case "3":
        indexes.push(0);
        break;
      default:
        return;
    }
    if (indexes.length === 0) {
      const keysMap = selectedKeys.reduce((map, k) => {
        map[k] = true;
        return map;
      }, {});
      dataSource.forEach((v, i) => {
        if (keysMap[v.code]) {
          indexes.push(i);
        }
      });
    }
    return indexes;
  };

  onNoticeTypeChange = (v, candidateUsers, variableDataSource) => {
    const { handleNoticeTypeChange } = this.props;
    const indexes = this.getSelectIndexes(candidateUsers, variableDataSource);
    handleNoticeTypeChange(this.noticeMap[v], indexes);
  };

  getNoticeSelectorStatus = (
    noticeChannel,
    candidateUsers,
    variableDataSource,
  ) => {
    const {
      activeKey,
      selectedSTAKeys = [],
      selectedVARKeys = [],
    } = this.state;
    const indexes = this.getSelectIndexes(candidateUsers, variableDataSource);
    const channels = Array.from(
      new Set(
        indexes
          .map((i) => (noticeChannel[i] && noticeChannel[i].code) || null)
          .filter(Boolean),
      ),
    );
    switch (activeKey) {
      case "1":
        return {
          visible: selectedSTAKeys.length > 0,
          value: channels.length === 1 ? channels[0] : null,
        };
      case "2":
        return {
          visible: selectedVARKeys.length > 0,
          value: channels.length === 1 ? channels[0] : null,
        };
      case "3":
        return {
          visible: true,
          value: (noticeChannel[0] && noticeChannel[0].code) || null,
        };
      default:
        return false;
    }
  };

  render() {
    const {
      activeKey,
      candidateUsersVisible,
      selectedSTAKeys = [],
      selectedVARKeys = [],
      // selectedRELKeys = [],
      visible,
      // relationPopVisible,
    } = this.state;
    const {
      appId,
      disable,
      dispatch,
      handleUsersSelect,
      modelVariables = [],
      noticeTypeData,
      selectedModel = {},
      // stackRadios = false,
    } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const {
      candidateUsers = [],
      // noticeChannel = [],
      relativeRelations = [],
    } = properties;
    const variableDataSource = candidateUsers.map(
      ({ name, code, varType: type }) => ({
        name,
        code,
        type,
      }),
    );
    const selectedVariablesMap = candidateUsers.reduce((map, { code }) => {
      map[code] = true;
      return map;
    }, {});
    const otherVariables = modelVariables
      .filter((v) => ["STA", "ORG", "ROL"].indexOf(v.type) > -1)
      .filter((v) => !selectedVariablesMap[v.code]);
    // const {
    //   visible: showNoticeSelector,
    //   value: noticetype,
    // } = this.getNoticeSelectorStatus(
    //   noticeChannel,
    //   candidateUsers,
    //   variableDataSource
    // );
    return (
      <>
        <Tabs
          activeKey={activeKey}
          className={`${styles.root} ${disable ? styles.disabled : ""}`}
          onChange={this.onTab}
          size="small"
        >
          <TabPane
            tab={
              <>
                从组织库中选择
                {activeKey === "1" && candidateUsers.length > 0 && (
                  <Icon type="check" />
                )}
              </>
            }
            key="1"
          />
          <TabPane
            tab={
              <>
                从变量中获取
                {activeKey === "2" && variableDataSource.length > 0 && (
                  <Icon type="check" />
                )}
              </>
            }
            key="2"
          />
          <TabPane
            tab={
              <>
                相对关系
                {activeKey === "3" && relativeRelations.length > 0 && (
                  <Icon type="check" />
                )}
              </>
            }
            key="3"
          />
        </Tabs>
        {activeKey === "1" && (
          <>
            <Table
              style={{ marginTop: 18 }}
              columns={[
                { title: "名称", dataIndex: "name" },
                {
                  title: "类型",
                  dataIndex: "type",
                  render: (v) => {
                    return typeLabelMap[v];
                  },
                },
              ]}
              dataSource={candidateUsers}
              pagination={{
                pageSize: 5,
              }}
              rowKey="code"
              rowSelection={{
                fixed: true,
                getCheckboxProps: () => ({
                  disabled: disable,
                }),
                onChange: (keys) => {
                  if (disable) return;
                  this.setState({ selectedSTAKeys: keys });
                },
                selectedRowKeys: selectedSTAKeys,
              }}
              size="small"
            />
            {this.renderButtons("STA", candidateUsers)}
          </>
        )}
        {activeKey === "2" && (
          <>
            <Table
              columns={[
                {
                  title: "名称",
                  dataIndex: "name",
                  render: (v) => (
                    <span className={styles.shortCell} title={v}>
                      {v}
                    </span>
                  ),
                },
                {
                  title: "编码",
                  dataIndex: "code",
                  render: (v) => (
                    <span className={styles.shortCell} title={v}>
                      {v}
                    </span>
                  ),
                },
                {
                  title: "类型",
                  dataIndex: "type",
                  render: (v) => {
                    const typeOption = typeOptions.filter(
                      (o) => o.value === v,
                    )[0] || { label: "" };
                    return typeOption.label;
                  },
                },
              ]}
              dataSource={variableDataSource}
              pagination={{
                pageSize: 5,
              }}
              rowKey="code"
              rowSelection={{
                fixed: true,
                getCheckboxProps: () => ({ disabled: disable }),
                onChange: (selected) => {
                  if (disable) return;
                  this.setState({ selectedVARKeys: selected });
                  // this.onNoticeTypeChange(noticetype, candidateUsers, variableDataSource);
                },
                selectedRowKeys: selectedVARKeys,
              }}
              size="small"
            />
            {this.renderButtons("VAR", candidateUsers)}
          </>
        )}
        {activeKey === "3" && (
          <>
            {/* <Table
              style={{ marginTop: 18 }}
              columns={this.relationColumns}
              dataSource={relativeRelations}
              pagination={{
                pageSize: 5,
              }}
              rowKey={record => relativeRelations.indexOf(record)}
              rowSelection={{
                fixed: true,
                getCheckboxProps: () => ({
                  disabled: disable,
                }),
                onChange: keys => {
                  if (disable) return;
                  this.setState({ selectedRELKeys: keys });
                },
                selectedRowKeys: selectedRELKeys,
              }}
              size="small"
            />
            {this.renderButtons("REL", relativeRelations)} */}
            <RadioGroup
              disabled
              style={{ fontSize: "14px", marginTop: 18 }}
              value="INIT"
            >
              <Radio value="INIT">允许流程发起人完成任务</Radio>
            </RadioGroup>
          </>
        )}
        {/* {showNoticeSelector ? (
          <div className={styles.notice}>
            <h1>通知渠道：</h1>
            <RadioGroup
              className={stackRadios ? styles.stack : ""}
              disabled={disable}
              style={{ fontSize: "12px" }}
              value={noticetype}
              onChange={e =>
                !disable &&
                this.onNoticeTypeChange(
                  e.target.value,
                  candidateUsers,
                  variableDataSource
                )
              }
            >
              {noticeTypeData.map(({ code, name }) => (
                <Radio key={code} value={code}>
                  {name}
                </Radio>
              ))}
            </RadioGroup>
          </div>
        ) : null} */}
        <TransactorSelect
          appId={appId}
          dispatch={dispatch}
          visible={candidateUsersVisible}
          selectData={candidateUsers}
          onCancel={() => this.handleUserVisible(false)}
          userSelect={(data) => {
            handleUsersSelect(data, noticeTypeData[0]);
            this.handleUserVisible(false);
          }}
          wrapClassName={styles.user_modal}
        />
        <FlowParamsSelector
          value={otherVariables}
          visible={visible}
          onOk={(rows) =>
            this.onAddVariables(rows, candidateUsers, selectedModel)
          }
          onCancel={() => this.handleVarVisible(false)}
        />
        {/*
        <FlowRelationSelector
          value={otherVariables}
          visible={relationPopVisible}
          onOk={(param) => this.onAddRelation(param, relativeRelations)}
          onCancel={() => this.handleRelationVisible(false)}
        />
        */}
      </>
    );
  }
}

export default UserTaskSelector;
